package com.sales.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import com.sales.client.StaffSalesClient;
import com.sales.service.SalesSlipDetService;
import com.sales.service.SalesSlipService;

import com.sales.util.UniqueOrderCode;
import org.comple.erp.pojo.sales.SalesSlip;
import org.comple.erp.pojo.sales.SalesSlipDet;
import org.comple.erp.remote.sales.GetSaleSlipRemote;
import org.comple.erp.utils.AjaxResult;
import org.comple.erp.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

@Component
@RestController
public class SalesSlipController implements GetSaleSlipRemote {
    @Autowired
    private SalesSlipService salesSlipService;
    @Autowired
    private SalesSlipDetService salesSlipDetService;
    @Autowired
    private UniqueOrderCode uniqueOrderCode;
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private StaffSalesClient staffSalesClient;

    @RequestMapping("/selectSlipList")
    public AjaxResult selectSlipList(@RequestParam Map<String, Object> params, HttpServletRequest  request){
        String token = request.getHeader("Authorization");
        String companyCode = JwtUtil.getCompanyCode(token);
        String userId = JwtUtil.getUserId(token);
        params.put("company_code", companyCode);
        Map<String, Object> staff = (Map<String, Object>) staffSalesClient.selectById(userId).get("staff");
        List<String> list = (List<String>) staff.get("roleIds");
        for (String roleId : list) {
            if (roleId.equals("2")) {
                params.put("workNumber", staff.get("id"));
            }
        }
        PageInfo<SalesSlip> selectSlipList = salesSlipService.selectSlipList(params);
        return AjaxResult.back("200","查询成功").add("selectSlipList",selectSlipList);
    }


    @PostMapping("/salesSlipAdd") // 建议明确使用 @PostMapping
    public synchronized AjaxResult salesSlipAdd( @RequestBody Map<String, Object> params,HttpServletRequest request) throws InterruptedException {


        String token = request.getHeader("Authorization");
        String companyCode = JwtUtil.getCompanyCode(token);
        String userId = JwtUtil.getUserId(token);


        // 提取并转换主表数据
        Map<String, Object> salesSlipMap = (Map<String, Object>) params.get("salesSlip");
        List<Map<String, Object>> salesSliptMapList = (List<Map<String, Object>>) params.get("salesSlipDetList");

        if (salesSlipMap == null || salesSliptMapList == null) {
            return AjaxResult.back("500", "参数错误");
        }

        // 转换为主表对象
        SalesSlip salesSlip = objectMapper.convertValue(salesSlipMap, SalesSlip.class);
        salesSlip.setId(UUID.randomUUID().toString());
        salesSlip.setCompany_code(companyCode);
        salesSlip.setWorkNumber(userId);
        String salesSlipCode = null;
        if(salesSlip.getIsReturn()==0){
            salesSlipCode= "XHD"+uniqueOrderCode.getCode("cd001", "SALESSLIP");
        }else if(salesSlip.getIsReturn()==1){
            salesSlipCode= "XHTH"+uniqueOrderCode.getCode("cd001", "RETURNSLIP");
        }

        if(salesSlip.getIsReturn()==0){
            salesSlip.setCode(salesSlipCode);
        }else if(salesSlip.getIsReturn()==1){
            salesSlip.setReturnCode(salesSlipCode);
        }

        // uniqueOrderCode.getCode(quotation.getCompany_code(), "QUOTATION");

        // 转换为明细列表
        List<SalesSlipDet> salesSlipDetList = salesSliptMapList.stream()
                .map(map -> objectMapper.convertValue(map, SalesSlipDet.class))
                .collect(Collectors.toList());

        salesSlip.setWritten_off_amount(salesSlip.getThisPayment());
        // 保存数据
        Boolean flag = salesSlipService.insertSelective(salesSlip);
        if (!flag) {
            return AjaxResult.back("500", "报价单添加失败");
        }

        // 保存明细数据
        for (SalesSlipDet slipDet : salesSlipDetList ) {
            if (salesSlip.getIsReturn()==0){
                slipDet.setSalesSlip_code(salesSlip.getCode());
            }else {
                slipDet.setSalesSlipReturnCode(salesSlip.getReturnCode());
            }

            slipDet.setId(UUID.randomUUID().toString());
            if (!salesSlipDetService.insertSelective(slipDet)) {
                return AjaxResult.back("500", "报价单详情添加失败");
            }
        }
        return AjaxResult.back("200", "添加成功").add("salesSlipCode", salesSlipCode).add("id", salesSlip.getId());

    }

    @PostMapping("/salesSlipUpdate")
    public synchronized AjaxResult salesSlipUpdate(@RequestBody Map<String, Object> request) throws InterruptedException {
        // 提取并转换主表数据
        Map<String, Object> salesSlipMap = (Map<String, Object>) request.get("salesSlip");
        List<Map<String, Object>> salesSliptMapList = (List<Map<String, Object>>) request.get("salesSlipDetList");

        if (salesSlipMap == null || salesSliptMapList == null) {
            return AjaxResult.back("500", "参数错误");
        }

        // 转换为主表对象
        SalesSlip salesSlip = objectMapper.convertValue(salesSlipMap, SalesSlip.class);
//        uniqueOrderCode.getCode(quotation.getCompany_code(), "QUOTATION");


        // 转换为明细列表
        List<SalesSlipDet> salesSlipDetList = salesSliptMapList.stream()
                .map(map -> objectMapper.convertValue(map, SalesSlipDet.class))
                .collect(Collectors.toList());

        salesSlip.setWritten_off_amount(salesSlip.getThisPayment());
        // 保存数据
        Boolean flag = salesSlipService.updateByPrimaryKeySelective(salesSlip);
        if (!flag) {
            return AjaxResult.back("500", "报价单修改失败");
        }

        Map<String, Object> params = new HashMap<>();
        if(salesSlipDetList != null && salesSlipDetList.size() > 0 && salesSlip.getIsReturn()==0){
            params.put("salesSlip_code", salesSlip.getCode());
        } else {
            params.put("salesSlipReturnCode", salesSlip.getReturnCode());
        }
        salesSlipDetService.deleteByCode(params);


        // 保存明细数据
        for (SalesSlipDet slipDet : salesSlipDetList ) {
            slipDet.setId(UUID.randomUUID().toString());
            if (salesSlip.getIsReturn()==0){
                slipDet.setSalesSlip_code(salesSlip.getCode());
            }else {
                slipDet.setSalesSlipReturnCode(salesSlip.getReturnCode());
            }

            if (!salesSlipDetService.insertSelective(slipDet)) {
                return AjaxResult.back("500", "报价单详情修改失败");
            }
        }
        return AjaxResult.back("200", "修改成功");
    }


    @RequestMapping("/selectSalesSlip")
    public AjaxResult selectSalesSlip(@RequestParam String id) {
        SalesSlip salesSlip = salesSlipService.selectByPrimaryKey(id);
        Map<String, Object> params = new HashMap<>();
        if(salesSlip.getIsReturn()==0){
            params.put("salesSlip_code", salesSlip.getCode());
        }else if(salesSlip.getIsReturn()==1){
            params.put("salesSlipReturnCode", salesSlip.getReturnCode());
        }

        List<SalesSlipDet> salesSlipDetList = salesSlipDetService.selectBySalesSlipCode(params);
        if(salesSlip != null && salesSlipDetList != null){
            return AjaxResult.back("200","查询成功").add("salesSlip", salesSlip).add("salesSlipDetList", salesSlipDetList);
        }
        return AjaxResult.back("500","查询失败");
    }

    @RequestMapping("deleteSalesSlip")
    public AjaxResult deleteSalesSlip(@RequestBody  List< String>  id) {
        for(String c : id){
            Boolean flag = salesSlipService.deleteByPrimaryKey(c);
            if (!flag) {
                return AjaxResult.back("500", "删除失败");
            }
        }
        return AjaxResult.back("200", "删除成功");
    }

    // 远程调用 拿到已审核的销售单
    @Override
    public AjaxResult getSaleSlipList(String customer_code) {
        List<SalesSlip> salesSlipList = salesSlipService.getSaleSlipList(customer_code);
        return AjaxResult.success().add("salesSlipList", salesSlipList);
    }

    //远程调用 拿到销售单
    @Override
    public AjaxResult getSaleSlip(String code) {
        List<SalesSlip> salesSlipList = salesSlipService.getSaleSlip(code);
        return AjaxResult.success().add("salesSlipList", salesSlipList);
    }

    @Override
    public AjaxResult updateSlipList(Map<String, Object>  params) {
        Boolean flag = salesSlipService.updateSlipList(params);
        if(flag){
            return AjaxResult.success();
        }
        return AjaxResult.error();
    }
}
